package com.sright.bcard.common.service.share.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.PutObjectRequest;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.List;


public class AliyunUitls {
    /**
     * 创建oss实例
     * @return
     */
    public static OSS getClient() {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = "LTAI4FtjPgprxNa6jJD2bbYV";
        String accessKeySecret = "N31zQesnC4r3JZ94l4inCswzdBZraj";

        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }
    public static String uploadLocalFile(String bucket, String object, String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = getClient();
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, object, new File(fileName));

        // 上传文件。
        ossClient.putObject(putObjectRequest);

        // 设置URL过期时间为1小时。
        Date expiration = new Date(new Date().getTime() + 86400 * 1000);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucket, object, expiration);
        // 关闭OSSClient。
        ossClient.shutdown();
        return url.toString();

    }

    public static void deleteSingleFile(String bucket, String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = getClient();
        ossClient.deleteObject(bucket,objectName);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    public static void deleteFileList(String bucket, List<String> objectNameList) {
        // 创建OSSClient实例。
        OSS ossClient = getClient();
        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucket).withKeys(objectNameList));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
        for (String result : deletedObjects) {
            System.out.println(result);
        }
        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
